package avicit;

import org.apache.rocketmq.client.producer.DefaultMQProducer;

import java.util.HashMap;
import java.util.Map;
//import org.apache.rocketmq.tools.admin.DefaultMQAdminExt;

public class RocketMQProducer2 {
    private static final String BROKER_NAME = "broker-a";
    private static final String TOPIC_NAME = "TestTopic";
    public static void main(String[] args) {
        DefaultMQProducer producer = new DefaultMQProducer("TempProducerGroup");
        producer.setNamesrvAddr("10.216.38.233:8000");
        createAndShutdownProducer(producer);
    }

    public static void createAndShutdownProducer(DefaultMQProducer producer) {
        try {
            producer.start();
            // 创建Topic（队列数8，权限读写）
            // 创建包含Broker属性的Map（新版本必须参数）
            Map<String, String> attributes = new HashMap<>();
            attributes.put("perm", "6");  // 读写权限
            attributes.put("order", "false"); // 非顺序消息

            producer.createTopic(BROKER_NAME, TOPIC_NAME, 8, attributes);

            // 发送100条消息
            for (int i = 0; i < 100; i++) {
                String messageBody = "Hello RocketMQ " + i;
                org.apache.rocketmq.common.message.Message msg = new org.apache.rocketmq.common.message.Message(TOPIC_NAME, "TagA", messageBody.getBytes());

                try {
                    producer.send(msg);
                    System.out.println("已发送消息: " + messageBody);
                } catch (Exception e) {
                    System.err.println("消息发送失败: " + messageBody);
                    e.printStackTrace();
                }

                // 可选：加个短暂休眠防止消息发送过快
                Thread.sleep(10);
            }
        } catch (Exception e) {
            // 记录异常信息，便于排查
            System.err.println("创建Topic时发生异常: " + e.getMessage());
            e.printStackTrace();
            // 可根据业务需求决定是否重新抛出异常或进行其他处理
        } finally {
            producer.shutdown();
        }
    }
}
